<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="业务员" prop="cpersonId" class="!w-100%">
            <el-select v-model="formData.cpersonId" placeholder="请选择" filterable :disabled="formData.isDisabled" @change=" personChange()" >
              <el-option
                v-for="item in personList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" prop="cdepId" class="!w-100%">
            <el-tree-select
              v-model="formData.cdepId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id" 
              placeholder="请选择部门"
              :disabled="true"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="订单日期" prop="ddate" >
        <el-date-picker
          v-model="formData.ddate"
          type="date"
          value-format="x"
          placeholder="选择订单日期"
          :disabled="formData.isDisabled"
          class="!w-100%"
        />
      </el-form-item>
      </el-col>
      </el-row>

    <el-row :gutter="20">
     
      <el-col :span="8">

        <el-form-item label="供应商" prop="cvenId" class="!w-100%">
        <el-input v-model="formData.cvencodeName" placeholder="请选择供应商" :disabled="formData.isDisabled" @click="openDialog()"/>
      </el-form-item>


      </el-col>
      <el-col :span="8">
        <el-form-item label="备注" prop="cmemo" class="!w-100%">
        <el-input v-model="formData.cmemo" placeholder="请输入备注" :disabled="formData.isDisabled" />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="流水号" prop="code">
        <el-input v-model="formData.code" placeholder="自动生成" :disabled="true"/>
      </el-form-item>
      </el-col>
    </el-row>

    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="采购订单子" name="pomains">
        <PomainsForm ref="pomainsFormRef" :pid="formData.id" :isDisabled="formData.isDisabled"/>
      </el-tab-pane>
    </el-tabs>
    <div class="footer">
      <el-button @click="submitForm" type="primary" :isDisabled="formData.isDisabled" :disabled="formLoading || route.query.type === 'select'">确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
    <vendorForm ref="formRefAdd" @successVendor="handleSuccessVendor" />

  </div>
</template>

<script setup lang="ts">
import { PomainApi, PomainVO } from '@/api/wms/pomain';
import PomainsForm from './components/PomainsForm.vue';
import { defaultProps, handleTree } from '@/utils/tree';
import { getSimpleDeptList } from '@/api/system/dept';
import { VendorVO, getSimpleVendorList } from '@/api/wms/vendor';
import {PersonApi}  from '@/api/wms/person'
import { useRoute, useRouter } from 'vue-router';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useTagsViewStore } from '@/store/modules/tagsView'
import vendorForm from './components/VendorForm.vue';

defineOptions({
  name: 'pomainFormCreate',
});

const { push, currentRoute } = useRouter() // 路由

const route = useRoute();
const router = useRouter();
const { t } = useI18n(); // 国际化

const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  cpersonId: undefined,
  cdepId: undefined,
  cvenId: undefined,
  ddate: new Date().getTime(),
  cmemo: undefined,
  checkTime: undefined,
  checkBy: undefined,
  cpersonIds: [],
  cvenIds: [],
  isDisabled:false,
  cvencodeName:undefined
});
const formRef = ref(); // 表单 Ref
const formRules = reactive({
  cpersonId: [{ required: true, message: '业务员不能为空', trigger: 'blur' }],
  cdepId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  cvenId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  ddate: [{ required: true, message: '入库日期不能为空', trigger: 'blur' }],
});
/** 子表的表单 */
const subTabsName = ref('pomains');
const pomainsFormRef = ref();
const vendorList = ref([] as VendorVO[]); // 供应商列表
const deptList = ref<any[]>([]); // 部门树形结构
// 业务员数据列表
const personList = ref([])
onMounted(async () => {
  // 加载用户数据
  personList.value = await PersonApi.getPersonSimpleList();
  // 加载部门树
  deptList.value = handleTree(await getSimpleDeptList());
  // 加载供应商
  vendorList.value = await getSimpleVendorList();
  initFormData(route.query.id ? String(route.query.id) : undefined);
});
const { delView } = useTagsViewStore() // 视图操作

/** 初始化表单数据 */
const initFormData = async (id?: string) => {
  if (id) {  
    formLoading.value = true;
    try {
        formData.value = await PomainApi.getPomain(id);
      if(route.query.type=='select')
      {
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }else if(route.query.type=='update'){
        formData.value.isDisabled = false; // 修改时可以编辑
      formType.value = 'update';
      }else if(route.query.type=='create'){
      // formData.value.isDisabled = false; // 新增时可以编辑
      formType.value = 'create';
      resetForm();
      }else{
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }
    } finally {
      formLoading.value = false;
    }
  } else {
    // formData.value.isDisabled = false; // 创建时可以编辑
    resetForm();
    formType.value = 'create';
  }
};

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 校验子表单
  try {
    await pomainsFormRef.value.validate();
  } catch (e) {
    subTabsName.value = 'pomains';
    return;
  }
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as PomainVO;
    // 拼接子表的数据
    data.pomainss = pomainsFormRef.value.getData();
    if (formType.value === 'create') {
      await PomainApi.createPomain(data);
      ElMessage.success(t('common.createSuccess'));
    } else {
      await PomainApi.updatePomain(data);
      ElMessage.success(t('common.updateSuccess'));
    }

    delView(unref(currentRoute))
    push('/store/pomain');
  } finally {
    formLoading.value = false;
  }
};



/** 重置表单 */
const resetForm = () => {
  formData.value = {
    isDisabled: false,
    id: undefined,
    code: undefined,
    cpersonId: undefined,
    cdepId: undefined,
    cvenId: undefined,
    ddate: new Date().getTime(),
    cmemo: undefined,
    checkTime: undefined,
    checkBy: undefined,
    cpersonIds: [],
    cvenIds: [],
    cvencodeName:undefined
  };
  formRef.value?.resetFields();
};

/** 返回上一页 */
const goBack = () => {
  router.go(-1);
};

const personChange = () => {
  let person = personList.value.find(map => map.id === formData.value.cpersonId)
  formData.value.cdepId = person.deptId
}

const formRefAdd = ref(null); // 确保变量名唯一

const openDialog = () => {
  // 打开弹窗的逻辑
  formRefAdd.value.open(event);
};


const handleSuccessVendor = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);

  formData.value.cvenId = getFormData.VendorId
  formData.value.cvencodeName = getFormData.VendorName

};


</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>
